Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Abstraction in java

Abstraction Intro

Abstraction in Java is a fundamental concept that revolves around the idea of hiding complexity and showing only the essential features to the user. Here’s a detailed explanation:

What is Abstraction?

Abstraction is the process of hiding certain details and showing only essential information to the user. It simplifies interaction by hiding the complexity behind simple interfaces.

How is Abstraction Achieved in Java?

Abstraction in Java is achieved using abstract classes and interfaces. An abstract class is a restricted class that cannot be used to create objects; to access it, it must be inherited from another class. An abstract method, on the other hand, can only be used in an abstract class and does not have a body. The body is provided by the subclass (inherited from). Example of Abstraction in Java Here’s a simple example of abstraction in Java:
Basic example of abstraction in java oops concept // Abstract class abstract class Animal { // Abstract method (does not have a body) public abstract void animalSound(); // Regular method public void sleep() { System.out.println("Zzz"); } } // Subclass (inherit from Animal) class Pig extends Animal { public void animalSound() { // The body of animalSound() is provided here System.out.println("The pig says: wee wee"); } } class Main { public static void main(String[] args) { Pig myPig = new Pig(); // Create a Pig object myPig.animalSound(); myPig.sleep(); } }

Output

The pig says: wee wee Zzz
In this example, Animal is an abstract class that has an abstract method animalSound(). The class Pig extends Animal and provides the implementation for the animalSound() method.

Why and When to Use Abstraction?

Abstraction is used to achieve security - hide certain details and only show the important details of an object. It’s particularly useful when you want to provide a common interface for different implementations, which is a common scenario in design patterns. Remember, abstraction in Java is a powerful tool that helps manage complexity in large programs by hiding the implementation details and exposing only the necessary functionality.

  📌TAGS

★Class ★ Method ★ Object ★ java ★ oops ★Abstraction

Tutorials